import { EnumChatState, MyChatConversationResult, MyChatConversationRquestPageSearchRequest } from "@/apis/endpoint/model";
import { postMychatChats } from "@/apis/endpoint/myChat";
import GpContainer from "@/components/GpContainer";
import GpEmpty from "@/components/GpEmpty";
import GpFontIcon from "@/components/GpFontIcon";
import GpNavbar from "@/components/GpNavbar";
import GpVerticelLine from "@/components/GpVerticelLine";
import { NAVIGATION_BASE_LAYOUT } from "@/hooks/useLayout";
import { useNavigationOpacity } from "@/hooks/useNavigationOpacity";
import { Badge } from "@taroify/core";
import { Image, Navigator, ScrollView, Text, View } from "@tarojs/components";
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import { useImmer } from "use-immer";
import styles from "./index.module.css";
import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from "@tarojs/taro";
import { dateFormat } from "@/utils/date";
import { pageMapper } from "@/constants/pageMap";
import { useAuthStore } from "@/store";

export default function Index() {
  const authenticated = useAuthStore(state => state.userInfo?.memberId)
  const [opacity] = useNavigationOpacity()
  const [navigationHeight, setNavigationHeight] = useState(NAVIGATION_BASE_LAYOUT.navigationHeight + NAVIGATION_BASE_LAYOUT.statusBarHeight)
  const filterOptions: IOption<EnumChatState>[] = [
    { value: EnumChatState.默认, label: "全部" },
    { value: EnumChatState.待介入, label: "待介入" },
    { value: EnumChatState.匹配成功, label: "匹配成功" },
    { value: EnumChatState.不合适, label: "不合适" },
    { value: EnumChatState.已约面, label: "已约面" }
  ]
  const [list, setList] = useState<MyChatConversationResult[]>([])
  const [listSearch, setListSearch] = useImmer({
    memberState: EnumChatState.默认
  } as MyChatConversationRquestPageSearchRequest["search"])
  const listParams = useRef({
    page: {
      pageIndex: 1
    },
    search: {
      memberState: listSearch.memberState
    }
  } as MyChatConversationRquestPageSearchRequest)
  const hasNext = useRef(true)
  useDidShow(() => {
    searchList(true)
  })
  useReachBottom(() => {
    if (authenticated && hasNext) {
      listParams.current.page.pageIndex++
      searchList()
    }
  })
  usePullDownRefresh(() => {
    Taro.startPullDownRefresh()
    searchList(true)
    .finally(() => {
      Taro.stopPullDownRefresh()
    })
  })
  async function searchList(refresh = false) {
    if (refresh) listParams.current.page.pageIndex = 1
    try {
      const { items, count } = await postMychatChats(listParams.current).send()
      const nextList = listParams.current.page.pageIndex === 1 ? items : list.concat(items)
      setList(nextList)
      hasNext.current = count > nextList.length
    } catch (error) {
      if (listParams.current.page.pageIndex !== 1)
       listParams.current.page.pageIndex -= 1
    }
  }
  function renderTopFilter() {
    return (
      <View className="fixed left-0 right-0 p-[32px] flex flex-row flex-nowrap" style={{
        top: `${navigationHeight}px`,
        backgroundColor: `rgba(255, 255, 255, ${opacity})`
      }}>
        <View className="flex-1 w-0 box-border">
          <ScrollView
            scrollX
            scrollWithAnimation
            className="w-full box-border"
          >
            <View className="flex flex-row gap-[48px] flex-nowrap">
              {
                filterOptions.map(item => (
                  <View key={item.value} className="flex flex-col items-center gap-[12px] flex-none" onClick={() => {
                    if (listSearch.memberState === item.value) return
                    setListSearch(draft => {
                      draft.memberState = item.value
                    })
                    listParams.current.search.memberState = item.value
                    searchList(true)
                  }}>
                    <Text className={clsx("text-[28px]", listSearch.memberState === item.value ? "text-theme font-bold" : "text-secondary")}>
                      {item.label}
                    </Text>
                    { listSearch.memberState === item.value && <GpVerticelLine width={32} height={8} className="rounded-[4px]"/>}
                  </View>
                ))
              }
            </View>
          </ScrollView>
        </View>
        <View className="flex flex-row items-start gap-[8px] flex-none">
          <GpFontIcon name="icon-shaixuan" size={28} className="text-third pt-[4px]" />
          <Text className="text-[28px] text-third">筛选</Text>
        </View>
      </View>
    )
  }
  function renderContent() {
    return (
      <View className="box-border">
        <Image src="/static/images/common/home-bg.png" className="h-[400px] w-[750px] object-cover" />
        {list.length > 0 ? renderList() : renderEmpty()}
      </View>
    )
  }
  function renderEmpty() {
    return (
      <GpEmpty
        description="暂无消息记录"
        imageProps={{src: "/static/images/chat/no-chat.png", className: "w-[280px] h-[200px]"}}
        emptyProps={{className: "mt-[180px]"}}
      />
    )
  }
  function renderList() {
    return (
      <View className="-mt-[96px]">
        <View className="flex flex-col gap-[64px]">
          {
            list.map(item => (
              <Navigator url={`/${pageMapper.chat.detail}?id=${item.id}`} key={item.id} className="flex flex-row items-center gap-[24px] px-[32px]">
                <Badge content={item.unreadCount || null} className={styles.badgeItem}>
                  <Image src={item.userAvatar ?? __DEF_AVATAR__} className="size-[96px] rounded-[50%] object-cover flex-none" />
                </Badge>
                <View className="flex-1 w-0 box-border">
                  <View className="flex flex-row items-center">
                    <View className="text-[32px] leading-[32px] text-black font-medium flex-none">{item.userName}</View>
                    <View className="flex-1 w-0 truncate text-[24px] leading-[24px] text-secondary ml-[8px] mr-[18px]">{item.companyName}</View>
                    {renderState(item)}
                  </View>
                  <View className="flex flex-row items-center gap-[28px] mt-[16px]">
                    <View className="text-third text-[28px] leading-[28px] truncate flex-1 w-0">{item.lastMessage}</View>
                    <View className="flex-none text-placeholder text-[24px] leading-[24px]">{dateFormat(item.lastTime, "short")}</View>
                  </View>
                </View>
              </Navigator>
            ))
          }
        </View>
        <GpVerticelLine width={686} height={2} color="#EEEEEE" className="mt-[64px]" />
        <View className="text-center text-placeholder text-[24px] leading-[24px] py-[48px]">
          仅显示30天内的聊天记录
        </View>
      </View>
    )
  }
  function renderState(item: MyChatConversationResult) {
    if (item.memberState === EnumChatState.不合适) {
      return (
        <View className="flex-none box-border flex flex-row items-center gap-[8px] h-[40px] pl-[12px] rounded-l-[20px] bg-linear-90 from-0% from-[#F53F3F]/8 to-100% to-[#F53F3F]/0 text-[#F53F3F]">
          <GpFontIcon name="icon-xiaozhibiaotizhuangshi" size={24} className="text-inherit" />
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">{item.matchScore}%</Text>
          <GpVerticelLine width={2} height={16} color="rgba(245, 63, 63, 0.5)" />
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">不合适</Text>
        </View>
      )
    } else if (item.memberState === EnumChatState.匹配成功) {
      return (
        <View className="flex-none box-border flex flex-row items-center gap-[8px] h-[40px] pl-[12px] rounded-l-[20px] bg-linear-90 from-0% from-[#0DAF7B]/8 to-100% to-[#0DAF7B]/0 text-[#0DAF7B]">
          <GpFontIcon name="icon-xiaozhibiaotizhuangshi" size={24} className="text-inherit" />
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">{item.matchScore}%</Text>
          <GpVerticelLine width={2} height={16} color="rgba(13, 175, 123, 0.5)" />
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">匹配成功</Text>
        </View>
      )
    } else if (item.memberState === EnumChatState.待介入) {
      return (
        <View className="flex-none box-border flex flex-row items-center gap-[8px] h-[40px] pl-[12px] rounded-l-[20px] bg-linear-90 from-0% from-theme/8 to-100% to-theme/0 text-theme">
          <GpFontIcon name="icon-xiaozhibiaotizhuangshi" size={24} className="text-inherit" />
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">{item.matchScore}%</Text>
          <GpVerticelLine width={2} height={16} color="rgba(7, 104, 250, 0.5)" />
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">待介入</Text>
        </View>
      )
    } else if (item.memberState === EnumChatState.已约面) {
      return (
        <View className="flex-none box-border flex flex-row items-center gap-[8px] h-[40px] pl-[12px] rounded-l-[20px] bg-linear-90 from-0% from-theme/8 to-100% to-theme/0 text-[#496EA9]">
          <Text className="text-inherit text-[24px] leading-[24px] font-medium">已约面</Text>
        </View>
      )
    } else {
      return null
    }
  }
  return <GpContainer className="bg-white">
    <GpNavbar
      navigationBarTitleText="聊天"
      navigationBarPlaceholder={false}
      navigationBarBackgroundColor={`rgba(255, 255, 255, ${opacity})`}
      onLayout={({statusBarHeight, navigationHeight}) => setNavigationHeight(statusBarHeight + navigationHeight)}
    />
    {renderTopFilter()}
    {renderContent()}
  </GpContainer>
}
